<?php
/************************
* Simple News Engine 0.2.3
* author: Ragnaar <ragnaar@km.ru>
* home: http://code.google.com/p/sne-news
* date: 08.06.2011
*********************/
define('_VALID_SNE', '1');
define('SNE_PATH', dirname(__FILE__)); //определяем путь

//включаем конфиг и конектор с базой
require_once SNE_PATH."/inc/config.php";
require_once SNE_PATH."/inc/lng/".$language.".php";
require_once SNE_PATH."/inc/connect.php";

//авторизация в админке
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Directory Listing"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>Access denied!</h2></body></html>';
    exit;
} else {
    $UserName = $_SERVER['PHP_AUTH_USER'];
    $UserPswd = $_SERVER['PHP_AUTH_PW'];
}
if ($UserName == $admlogin && $UserPswd == $admpassword) {
} else {
    echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>Access denied!</h2></body></html>';
    exit;
}

//включаем функции и класс для постраничной навигации
require_once SNE_PATH."/inc/functions.php";
require_once SNE_PATH."/inc/pager.class.php";
require_once SNE_PATH."/inc/js.php";

//определяем шаблоны
$adm_header_tpl = SNE_PATH."/inc/tpl/adm_header.tpl";
$adm_footer_tpl = SNE_PATH."/inc/tpl/adm_footer.tpl";

//определяем действие

$modes = array('view', 'edit', 'delete', 'public', 'add', 'image'); // все режимы
if (isset($_GET['action']) && in_array($_GET['action'], $modes)) {
    $action = $_GET['action'];
} else {
    $action = 'view'; //по умолчанию - просмотр
}

if (isset($_GET['p']) && $_GET['p'] > 0){ //определяем страницу
    $page = (int)$_GET['p'];
} else {
    $page = 1;
}

if (isset($_GET['order']) && $_GET['order'] > 0){ //определяем сортировку
    $order = (int)$_GET['order'];
} else {
    $order = 1;
}

/************************
* View action
*********************/
if ($action == "view"){

    $start = ($page - 1) * $vw_news_num; //для постраничного вывода

    switch($order){
        case 1;
            $sort = "`id` DESC";
            break;
        case 2;
            $sort = "`title`";
            break;
        case 3;
            $sort = "`date`";
            break;
        case 4;
            $sort = "`image` DESC";
            break;
        case 5;
            $sort = "`pub`";
            break;
        default;
            $sort = "`id` DESC";
    }

    $tot = mysql_query(prefix("SELECT count(*) FROM `{prefix}news`", $dbprefix)); //запрос количества новостей
    $query = prefix("SELECT * FROM `{prefix}news` ORDER BY $sort LIMIT $start, $vw_news_num", $dbprefix); //формируем запрос для получения новостей

    $thm = mysql_query($query);  //получаем новости

    if($tot && $thm){
        $total = mysql_fetch_array($tot);
        $count = $total['count(*)']; //общее количество новостей в базе
    }

    $title = _SNE_PAGE_MODE;
    $header = $deleteJs; //JavaScript
    include $adm_header_tpl; //инклюдим заголовок
?>
<form action="" method="POST">
	<div class="panel">
		<a href="?action=add"><img src="./img/add.png" alt="<?php echo _SNE_ADD ?>" title="<?php echo _SNE_ADD ?>" /></a>
	</div>
	<table border="1" id="listing">
		<colgroup>
			<col width="5">
			<col width="305">
			<col width="10">
			<col width="100">
			<col width="10">
			<col width="10">
			<col width="10">
			<col width="10">
		</colgroup>
		<tr>
			<th>№</th>
			<th><a href="?action=view&amp;order=2&amp;p=<?php echo $page ?>"><?php echo _SNE_TITLE ?></a></th>
			<th><a href="?action=view&amp;order=1&amp;p=<?php echo $page ?>"><?php echo _SNE_ID ?></a></th>
			<th><a href="?action=view&amp;order=3&amp;p=<?php echo $page ?>"><?php echo _SNE_DATE ?></a></th>
			<th><a href="?action=view&amp;order=4&amp;p=<?php echo $page ?>"><?php echo _SNE_IMG ?></a></th>
			<th><a href="?action=view&amp;order=5&amp;p=<?php echo $page ?>"><?php echo _SNE_PUB ?></a></th>
			<th><?php echo _SNE_EDIT ?></th>
			<th><?php echo _SNE_DEL ?></th>
		</tr>
<?php
//выводим список новостей таблицей
    for($i = 1; $i <= $vw_news_num; $i++) {
        $row = mysql_fetch_object($thm);
        if(!$row){
           break;
        }
    	if($i % 2 == 0) {  //определяем четность
            echo "\t\t<tr class='num'>\n";
        } else {
            echo "\t\t<tr>\n";
        }
        $number = $i + $start;
        echo "\t\t\t<td>".$number."</td>\n";
        echo "\t\t\t<td><a href='adm.php?action=edit&amp;id=".$row->id."&amp;p=".$page."'>".$row->title."</a></td>\n";
        echo "\t\t\t<td>".$row->id."</td>\n";
        echo "\t\t\t<td>".$row->date."</td>\n";
        echo "\t\t\t<td>";
        if ($row->image){
            echo "<a href='adm.php?action=image&amp;id=".$row->id."&amp;p=".$page."'><img src='./img/image.png' alt='"._SNE_IMAGE."' title='"._SNE_IMAGE."' /></a>";
        } else {
            echo "&nbsp;";
        }
        echo "</td>\n";
        echo "\t\t\t<td><a href='adm.php?action=public&amp;id=".$row->id."&amp;p=".$page."'>";
        if ($row->pub == 1){
            echo "<img src='./img/public.png' alt='"._SNE_PUBLIC."' title='"._SNE_PUBLIC."' />";
        } else {
            echo "<img src='./img/unpublic.png' alt='"._SNE_UNPUBLIC."' title='"._SNE_UNPUBLIC."' />";
        }
        echo "</a></td>\n";
        echo "\t\t\t<td><a href='adm.php?action=edit&amp;id=".$row->id."&amp;p=".$page."'><img src='./img/edit.png' alt='"._SNE_EDIT2."' title='"._SNE_EDIT2."' /></a></td>\n";
        echo "\t\t\t<td><a href='javascript:void()' onClick='Delete(".$row->id.", ".$page.")'><img src='./img/delete_s.png' alt='"._SNE_DELETE."' title='"._SNE_DELETE."' /></a></td>\n";
        echo "\t\t</tr>\n";
    }
?>
	</table>
</form>
<?php
        $total_records = $count; //Всего найдено

    if ($total_records > $vw_news_num){
        pager($total_records, $vw_news_num, $page, '?order='.$order.'&amp;p=');
    }

    include $adm_footer_tpl; //инклюдим подвал
}
/************************
* Edit action
*********************/
if ($action == "edit"){

    $id = (int)$_GET['id'];

    $rows = mysql_query(prefix("SELECT * FROM `{prefix}news` WHERE `id` = $id", $dbprefix)); //получаем выбранную новость
    $row = mysql_fetch_object($rows);

    if ($row->image){ // выводим загруженные изображения
        $imgs = mysql_query(prefix("SELECT * FROM `{prefix}images` WHERE `news_id` = $id ORDER BY `id`", $dbprefix)); //получаем картинки выбранной новости
        $num_imgs = mysql_num_rows($imgs); //считаем количество картинок
        $image = 1;
    } else {
    	$image = 0;
    }

    if (!$row->cut){
        $row->text = str_replace('<hr id="cut">', '', $row->text);
    }

    if (empty($_POST['pub'])) { //определяем чекбокс публикации
        $_POST['pub'] = 0;
    } else {
        $_POST['pub'] = 1;
    }

    if (isset($_POST['delete_x']) && isset($_POST['img'])){	 //удаление картинок
        delimg($_POST['img'], $id, $page, $num_imgs, $action);
    }

    if (isset($_POST['hide_x']) && isset($_POST['img'])){ //скрываем изображение
        hideimg($_POST['img'], $id, $page, $action);
    }

    if (isset($_POST['save_x']) || isset($_POST['apply_x'])){
        if (isset($_POST['image'])){ // добавление картинок
            $add_img = $_POST['image'];
            foreach($add_img as $add) {
                $query = prefix("INSERT INTO `{prefix}images` (`name`, `title`, `description`, `pub`, `news_id`) VALUES ('$add','', '', '1', '$id')", $dbprefix);
                $result = mysql_query($query) or die('can\'t add');
            }
            $image = 1;
        }
        if (isset($_POST['title']) && isset($_POST['text'])){
            if (strpos($_POST['text'], '<hr id="cut">')){
                $cuted = 1;
            } else {
                $cuted = 0;
                $_POST['text'] = $_POST['text'].'<hr id="cut">';
            }
            $query = prefix("UPDATE `{prefix}news` SET `title` = '".htmlspecialchars(trim($_POST['title']))."', `text` = '".mysql_real_escape_string($_POST['text'])."', `cut` = '".$cuted."', `image` = '".$image."', `date` = '".mysql_real_escape_string($_POST['date'])."', `pub` = '".$_POST['pub']."' WHERE `id` = '".$_POST['id']."';", $dbprefix);
            $result = mysql_query($query, $dbcnx);
        }
        if (isset($_POST['apply_x'])){
            $url = "adm.php?action=edit&id=".$id."&p=".$page; // редиректим сюда
        }
        if (isset($_POST['save_x'])){
            $url = "adm.php?p=".$page; // редиректим сюда
        }
        redirect($url);
    }

    $title = _SNE_EDIT_MODE; //текст заголовка
    $header = $jqueryJs.$cleditorJs.$imgboxJs.$uploadJs; //JavaScript
    include $adm_header_tpl; //инклюдим заголовок

?>
	<form action="" method="POST" id="editForm">
	    <div class="panel" id="news_panel">
		    <input type="image" name="save" value="yes" src="./img/save.png" alt="<?php echo _SNE_SAVE ?>" title="<?php echo _SNE_SAVE ?>" />
		    <input type="image" name="apply" value="yes" src="./img/apply.png" alt="<?php echo _SNE_APPLY ?>" title="<?php echo _SNE_APPLY ?>" />
		    <a href="./adm.php?p=<?php echo $page ?>"><img src="./img/cancel.png" alt="<?php echo _SNE_CANCEL ?>" title="<?php echo _SNE_CANCEL ?>" /></a>
	    </div>
		<input type="text" name="title" id="title" value="<?php echo $row->title; ?>" />
		<input type="checkbox" name="pub" value="1" <?php if ($row->pub == 1) echo " checked='1'"; ?> /><?php echo _SNE_PUBLISHED ?><br />
		<textarea name="text" id="text"><?php echo $row->text; ?></textarea>
		<input type="text" name="date" id="date" value="<?php echo $row->date; ?>" />
		<input type="hidden" name="id" value="<?php echo $row->id; ?>" />
		<input type="hidden" name="action" value="edit" />
<?php
		// выводим загруженные изображения
    if ($row->image){
?>
        <div class="panel" id="image_panel">
           <input type="image" name="hide" value="yes" src="./img/hide.png" alt="<?php echo _SNE_HIDE ?>" title="<?php echo _SNE_HIDE ?>" />
	       <input type="image" name="delete" value="yes" src="./img/delete.png" alt="<?php echo _SNE_DELETE ?>" title="<?php echo _SNE_DELETE ?>" />
	       <input type="image" name="apply" value="yes" src="./img/attach.png" alt="<?php echo _SNE_ATTACH ?>" title="<?php echo _SNE_ATTACH ?>" />
        </div>

        <div id="upimage">
<?php
        while($img = mysql_fetch_object($imgs)) {
            echo "\t\t\t<span class='att_image'><a href='./image/".$img->name."' class='imgbox'  id='img".$img->id."'>";
            if ($img->pub == 1){
                echo "<img src='./thumb/".$img->name."' alt='".$img->title."' title='".$img->description."' />";
            } else {
                echo "<img src='./thumb/".$img->name."' alt='".$img->title."' title='".$img->description."' class='hide' />";
            }
            echo "</a><br><input type='checkbox' name='img[]' value='".$img->id."'></span>\n";
        }
        echo "\t\t</div>\n";
    }
?>
	</form>
	<form name="pictureform" action="./inc/upload.php" method="post" enctype="multipart/form-data" target="upload_target" >
		<p id="f1_upload_process"><img src="./img/loader.gif" /></p>
		<p id="f1_upload_form">
			<label><?php echo _SNE_ADD_IMGS ?><input name="myfile" type="file" size="30" onchange="startUpload();document.pictureform.submit();" /></label>
		</p>
		<div id="thumbnails"></div>
		<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
	</form>

<?php
    include $adm_footer_tpl; //инклюдим подвал
}
/************************
* Public action
*********************/
if ($action == "public"){

    $id = (int)$_GET['id'];

    $rows = mysql_query(prefix("SELECT `pub` FROM `{prefix}news` WHERE `id` = $id", $dbprefix)); //получаем выбранную новость
    $row = mysql_result($rows, 0);

    if ($row == 1){
        $pub = 0;
    } else {
        $pub = 1;
    }

    $query = prefix("UPDATE `{prefix}news` SET `pub` = '$pub' WHERE `id` = $id", $dbprefix);
    mysql_query($query, $dbcnx);

    $url = "adm.php?p=".$page; // редиректим сюда
    redirect($url);
}
/************************
* Delete action
*********************/
if ($action == "delete"){

    $id = (int)$_GET['id'];

    $query = prefix("DELETE FROM `{prefix}news` WHERE `id` = $id", $dbprefix);
    mysql_query($query, $dbcnx);

    $url = "adm.php?p=".$page; // редиректим сюда
    redirect($url);
}
/************************
* Add action
*********************/
if ($action == "add"){

    if (isset($_POST['title']) && isset($_POST['text'])){
        if (strpos($_POST['text'], '<hr id="cut">')){
            $cuted = 1;
        } else {
            $cuted = 0;
            $_POST['text'] = $_POST['text'].'<hr id="cut">';
        }
        $query = prefix("INSERT INTO `{prefix}news` (`title`, `text`, `cut`, `date`, `pub`) VALUES ('".htmlspecialchars(trim($_POST['title']))."', '".mysql_real_escape_string($_POST['text'])."', '".$cuted."', '".mysql_real_escape_string($_POST['date'])."', '".$_POST['pub']."')", $dbprefix);
        mysql_query($query, $dbcnx);

        if($_POST['apply_x']){
            $url = 'adm.php?action=edit&id='.mysql_insert_id(); // редиректим сюда
        }
        if ($_POST['save_x']){
            $url = 'adm.php'; // редиректим сюда
        }
        redirect($url);
    }

    $title = _SNE_ADD_MODE; //текст заголовка
    $header = $jqueryJs.$cleditorJs; //JavaScript
    include $adm_header_tpl; //инклюдим заголовок
?>
	<form action="" method="POST">
	<div class="panel">
		<input type="image" name="save" value="yes" src="./img/save.png" alt="<?php echo _SNE_SAVE ?>" title="<?php echo _SNE_SAVE ?>" />
		<input type="image" name="apply" value="yes" src="./img/apply.png" alt="<?php echo _SNE_APPLY ?>" title="<?php echo _SNE_APPLY ?>" />
		<a href="./adm.php"><img src="./img/cancel.png" alt="<?php echo _SNE_CANCEL ?>" title="<?php echo _SNE_CANCEL ?>" /></a>
	</div>
		<input type="text" name="title" id="title" value="">
		<input type="checkbox" name="pub" value="1"><?php echo _SNE_PUBLISHED ?><br />
		<textarea name="text" id="text"></textarea>
		<input type="text" name="date" id="date" value="<?php echo date('Y-m-d H:i:s'); ?>">
		<input type="hidden" name="action" value="add">
	</form>
<?php
    include $adm_footer_tpl; //инклюдим подвал
}
/************************
* Image action
*********************/
if ($action == "image"){

    $id = (int)$_GET['id'];

    $imgs = mysql_query(prefix("SELECT * FROM `{prefix}images` WHERE `news_id` = $id ORDER BY `id`;", $dbprefix)); //получаем картинки выбранной новости
    $num_imgs = mysql_num_rows($imgs);

    $rows = mysql_query(prefix("SELECT `title` FROM `{prefix}news` WHERE `id` = $id", $dbprefix)); //получаем выбранную новость
    $row = mysql_result($rows, 0);

    if (isset($_POST['delete_x']) && isset($_POST['img'])){	 //удаление картинок
        delimg($_POST['img'], $id, $page, $num_imgs, $action);
    }

    if (isset($_POST['apply_x']) || isset($_POST['save_x'])){ // добавление картинок
        if (isset($_POST['image'])){
            addimg($_POST['image'], $id);
        }
        if (isset($_POST['apply_x'])){
            $url = "adm.php?action=image&id=".$id."&p=".$page; // редиректим сюда
        }
        if (isset($_POST['save_x'])){
            $url = "adm.php?p=".$page; // редиректим сюда
        }
        redirect($url);
    }

    if (isset($_POST['hide_x']) && isset($_POST['img'])){ //скрываем изображение
        hideimg($_POST['img'], $id, $page, $action);
    }

    $title = _SNE_IMAGE_MODE; //текст заголовка
    $header = $jqueryJs.$imgboxJs.$uploadJs; //JavaScript
    include $adm_header_tpl; //инклюдим заголовок

?>
	<form action="" method="POST" id="editForm">
	    <div class="panel">
  	        <input type="image" name="hide" value="yes" src="./img/hide.png" alt="<?php echo _SNE_HIDE ?>" title="<?php echo _SNE_HIDE ?>" />
	        <input type="image" name="delete" value="yes" src="./img/delete.png" alt="<?php echo _SNE_DELETE ?>" title="<?php echo _SNE_DELETE ?>" />
		    <input type="image" name="save" value="yes" src="./img/save.png" alt="<?php echo _SNE_SAVE ?>" title="<?php echo _SNE_SAVE ?>" />
		    <input type="image" name="apply" value="yes" src="./img/apply.png" alt="<?php echo _SNE_APPLY ?>" title="<?php echo _SNE_APPLY ?>" />
		    <a href="./adm.php?p=<?php echo $page ?>"><img src="./img/cancel.png" alt="<?php echo _SNE_CANCEL ?>" title="<?php echo _SNE_CANCEL ?>" /></a>

	    </div>
		<input type="hidden" name="action" value="image">
		<input type="hidden" name="id" value="<?php echo $id; ?>">
		<h3><?php echo $row; ?></h3>

<?php
    if (!$num_imgs == 0) {
		// выводим загруженные изображения
        echo "\t\t<p id='attach_img'>"._SNE_ATTACH_IMGS."</p>\n";
        echo "\t\t<div id='upimage'>\n";
        while($img = mysql_fetch_object($imgs)) {
            echo "\t\t\t<span class='att_image'><a href='./image/".$img->name."' class='imgbox'  id='img".$img->id."'>";
            if ($img->pub == 1){
                echo "<img src='./thumb/".$img->name."' alt='".$img->title."' title='".$img->description."' />";
            } else {
                echo "<img src='./thumb/".$img->name."' alt='".$img->title."' title='".$img->description."' class='hide' />";
            }
            echo "</a><br><input type='checkbox' name='img[]' value='".$img->id."'></span>\n";
        }
        echo "\t\t</div>\n";
    }
?>
	</form>
	<form name="pictureform" action="./inc/upload.php" method="post" enctype="multipart/form-data" target="upload_target" >
		<p id="f1_upload_process"><img src="./img/loader.gif" /></p>
		<p id="f1_upload_form">
			<label><?php echo _SNE_ADD_IMGS ?><input name="myfile" type="file" size="30" onchange="startUpload();document.pictureform.submit();" /></label>
		</p>
		<div id="thumbnails"></div>
		<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
	</form>
<?php
    include $adm_footer_tpl; //инклюдим подвал
}
?>
